package com.yanqu.road.dataHelper.action.crossunion;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dataHelper.gameServer.GameServer;
import com.yanqu.road.dataHelper.repair.BaseRepair;
import com.yanqu.road.entity.dto.CrossPatronsSkill;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.union.UnionConstruct;
import com.yanqu.road.entity.union.cross.*;
import com.yanqu.road.entity.union.parergon.UnionBussinessman;
import com.yanqu.road.entity.union.parergon.UnionBussinessmanDetail;
import com.yanqu.road.entity.union.parergon.UnionParergon;
import com.yanqu.road.entity.union.parergon.UnionParergonPlayer;
import com.yanqu.road.entity.union.trade.UnionTradeEventRead;
import com.yanqu.road.entity.union.trade.UnionTradeLog;
import com.yanqu.road.entity.union.trade.UnionTradeTeamData;
import com.yanqu.road.entity.union.trade.UnionTradeTeamUserJoin;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossUnionLogic extends BaseRepair {

    public CrossUnionLogic(GameServer gameServer) {
        super(gameServer);
    }

    @Override
    public void repair(long param1, String param2) {

    }

    /**
     * 商会
     */
    public List<CrossUnionInfo> getUnionInfoList(){
        PreparedStatement call = null;
        String sql = "select * from t_u_union";
        List<CrossUnionInfo> list = new ArrayList<>();
        try {
            call = getGameServer().getConnection().prepareStatement(sql);
            ResultSet rs = call.executeQuery();
            while (rs.next()) {
                CrossUnionInfo data = new CrossUnionInfo();
                data.setUnionUid(rs.getString("unionUid"));
                data.setUnionName(rs.getString("unionName"));
                data.setCreateTime(rs.getLong("createTime"));
                data.setOutNotice(rs.getString("outNotice"));
                data.setInnerNotice(rs.getString("innerNotice"));
                data.setExperience(rs.getLong("experience"));
                data.setMasterUserId(rs.getLong("ownerUserId"));
                data.setMasterNickName(rs.getString("ownerNickName"));
                data.setMasterJoinTime(rs.getLong("ownerJoinTime"));
                data.setWechatCode(rs.getString("wechatCode"));
                data.setQqCode(rs.getString("qqCode"));
                data.setMemberCount(rs.getInt("memberCount"));
                data.setAllowRandomJoin(rs.getBoolean("isAllowRandomJoin"));
                String value = rs.getString("totalEarnSpeed");
                if(!StringUtils.isNullOrEmpty(value)){
                    data.setTotalEarnSpeed(new BigInteger(value));
                }
                data.setWealth(rs.getLong("wealth"));
                data.setDelete(rs.getBoolean("isDelete"));
                data.setModifyTime(rs.getLong("modifyTime"));
                data.setUnionFightRewardMark(rs.getInt("unionFightRewardMark"));
                data.setUnionFlag(rs.getInt("unionFlag"));
                data.setFlagModifyTime(rs.getLong("flagModifyTime"));
                data.setConstructActive(rs.getInt("constructActive"));
                data.setVipExp(rs.getLong("vipExp"));
                data.setConstructUserIdList(StringUtils.stringToLongList(rs.getString("constructUserIdList"), ","));
                data.setUnionAliasId(rs.getLong("unionAliasId"));
                value = rs.getString("decoration");
                if(!StringUtils.isNullOrEmpty(value)){
                    data.setDecoration(value);
                }
                data.setRankActivityId(rs.getInt("rankActivityId"));
                data.setRankAddExp(rs.getLong("rankAddExp"));
                data.setPreUnionFlag(rs.getInt("preUnionFlag"));
                data.setDayJoinNum(rs.getInt("dayJoinNum"));
                data.setServerId(getGameServer().getServerInfo().getServerId());
                list.add(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            getGameServer().closeConnection(call, null);
        }
        return list;
    }

    /**
     * 成员
     */
    public List<CrossUnionMember> getUnionMemberList(){
        PreparedStatement call = null;
        String sql = "select * from t_u_union_member";
        List<CrossUnionMember> list = new ArrayList<>();
        try {
            call = getGameServer().getConnection().prepareStatement(sql);
            ResultSet rs = call.executeQuery();
            while (rs.next()) {
                CrossUnionMember data = new CrossUnionMember();
                data.setUnionUid(rs.getString("unionUid"));
                data.setUserId(rs.getLong("userId"));
                data.setPosition(rs.getInt("position"));
                String baseUserInfoStr = rs.getString("userBaseInfo");
                if(null == baseUserInfoStr){
                    baseUserInfoStr = "";
                }
                UserBaseInfo userBaseInfo = JSON.parseObject(baseUserInfoStr, new TypeReference<UserBaseInfo>() {});
                if(null != userBaseInfo) {
                    data.setUserBaseInfo(userBaseInfo);
                }
                data.setModifyTime(rs.getLong("modifyTime"));
                data.setContribution(rs.getLong("contribution"));
                data.setTotalContribution(rs.getLong("totalContribution"));
                data.setDonateTimes(rs.getInt("donateTimes"));
                data.setQuitTime(rs.getLong("quitTime"));
                data.setTodayContribution(rs.getInt("todayContribution"));
                data.setChamberPatronsId(rs.getInt("chamberPatronsId"));
                data.setConstructRewardIndexList(StringUtils.stringToIntegerList(rs.getString("constructRewardIndexList"), ","));
                String unionConstructData = rs.getString("unionConstructData");
                Map<Integer, UnionConstruct> unionConstructMap = new ConcurrentHashMap<>();
                if(!StringUtils.isNullOrEmpty(unionConstructData)){
                    unionConstructMap = JSON.parseObject(unionConstructData, new TypeReference<Map<Integer, UnionConstruct>>() {});
                }
                data.setUnionConstructMap(unionConstructMap);
                data.setServerId(getGameServer().getServerInfo().getServerId());
                list.add(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            getGameServer().closeConnection(call, null);
        }
        return list;
    }

    /**
     * 议事厅（新加表）
     */
    public List<CrossUnionChamberPatrons> getUnionChamberPatronsList(){
        PreparedStatement call = null;
        String sql = "select m.userId, p.patronsId, (select group_concat(CONCAT(skillId,',',skillLv,',',type,',',skinSkillLevel) SEPARATOR ';') from t_u_patrons_skill where userId = m.userId and patronsId = m.chamberPatronsId and isDelete = 0) as skillList," +
                "p.ability, p.`level`, p.stageLv, p.breakLv, p.skinId, p.promotionId " +
                "from t_u_union_member m left JOIN t_u_patrons p on m.chamberPatronsId = p.patronsId and m.userId = p.userId where m.chamberPatronsId > 0 and m.unionUid <> '';";
        List<CrossUnionChamberPatrons> resultList = new ArrayList<>();
        try {
            call = getGameServer().getConnection().prepareStatement(sql);
            ResultSet rs = call.executeQuery();
            while (rs.next()) {
                CrossUnionChamberPatrons data = new CrossUnionChamberPatrons();
                data.setUserId(rs.getLong("userId"));
                int patronsId = rs.getInt("patronsId");
                if (patronsId <= 0) {
                    continue;
                }
                data.setPatronsId(patronsId);
                String str = rs.getString("skillList");
                if(!StringUtils.isNullOrEmpty(str)){
                    List<String> skillList = StringUtils.stringToStringList(str, ";");
                    for (String skill : skillList) {
                        List<Integer> list = StringUtils.stringToIntegerList(skill, ",");
                        if(list.size() == 4){
                            CrossPatronsSkill patronsSkill = new CrossPatronsSkill();
                            patronsSkill.setId(list.get(0));
                            patronsSkill.setLv(list.get(1));
                            patronsSkill.setType(list.get(2));
                            patronsSkill.setSkinLv(list.get(3));
                            data.getSkillList().add(patronsSkill);
                        }
                    }
                }
                String ability = rs.getString("ability");
                if (ability == null) {
                    ability = "0";
                }
                data.setAbility(new BigInteger(ability));
                data.setLevel(rs.getInt("level"));
                data.setStageLv(rs.getInt("stageLv"));
                data.setBreakLv(rs.getInt("breakLv"));
                data.setSkinId(rs.getInt("skinId"));
                data.setPromotionId(rs.getInt("promotionId"));
                resultList.add(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            getGameServer().closeConnection(call, null);
        }
        return resultList;
    }

    /**
     * 商会动态
     */
    public List<CrossUnionNotice> getUnionNoticeList(){
        PreparedStatement call = null;
        String sql = "select * from t_u_union_notice where noticeTime> ?";
        long selectTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000 - DateHelper.DAY_SECONDS * 3;
        List<CrossUnionNotice> list = new ArrayList<>();
        try {
            call = getGameServer().getConnection().prepareStatement(sql);
            int i = 1;
            call.setLong(i++, selectTime);
            ResultSet rs = call.executeQuery();
            while (rs.next()) {
                CrossUnionNotice data = new CrossUnionNotice();
                data.setUnionUid(rs.getString("unionUid"));
                data.setType(rs.getInt("type"));
                data.setUserId(rs.getLong("userId"));
                data.setNickName(rs.getString("nickName"));
                data.setNoticeTime(rs.getLong("noticeTime"));
                data.setContent(rs.getString("content"));
                list.add(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            getGameServer().closeConnection(call, null);
        }
        return list;
    }

    /**
     * 商会旗帜
     */
    public List<CrossUnionFlag> getCrossUnionFlagList(){
        PreparedStatement call = null;
        String sql = "select * from t_u_union_flag";
        List<CrossUnionFlag> list = new ArrayList<>();
        try {
            call = getGameServer().getConnection().prepareStatement(sql);
            ResultSet rs = call.executeQuery();
            while (rs.next()) {
                CrossUnionFlag data = new CrossUnionFlag();
                data.setUnionUid(rs.getString("unionUid"));
                data.setFlagId(rs.getInt("flagId"));
                data.setExpireTime(rs.getLong("expireTime"));
                data.setRead(rs.getBoolean("isRead"));
                list.add(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            getGameServer().closeConnection(call, null);
        }
        return list;
    }

    /**
     * 商贸路线
     */
    public List<UnionTradeTeamData> getUnionTradeTeamDataList(){
        PreparedStatement call = null;
        String sql = "select * from t_u_union_trade_team";
        List<UnionTradeTeamData> list = new ArrayList<>();
        try {
            call = getGameServer().getConnection().prepareStatement(sql);
            ResultSet rs = call.executeQuery();
            while (rs.next()) {
                UnionTradeTeamData data = new UnionTradeTeamData();
                data.setUnionUid(rs.getString("unionUid"));
                data.setRouteId(rs.getInt("routeId"));
                data.setOpenUser(rs.getLong("openUser"));
                data.setOpenTime(rs.getLong("openTime"));
                data.setStartTradeTime(rs.getLong("startTradeTime"));
                data.setStateVal(rs.getInt("stateVal"));
                data.setFinishType(rs.getInt("finishType"));
                data.setSendReward(rs.getBoolean("sendReward"));
                data.setExpectReward(rs.getString("expectReward"));
                data.setReward(rs.getString("reward"));
                data.setEventReward(rs.getString("eventReward"));
                data.setLogDataList(JSONArray.parseArray(rs.getString("logDataList"), UnionTradeLog.class));
                data.setUserJoinDataList(JSONArray.parseArray(rs.getString("userJoinDataList"), UnionTradeTeamUserJoin.class));
                data.setUserReadList(JSONArray.parseArray(rs.getString("userReadList"), UnionTradeEventRead.class));
                data.setEventTimeList(StringUtils.stringToIntegerList(rs.getString("eventTimeList"), ";"));
                data.setEventList(StringUtils.stringToIntegerList(rs.getString("eventList"), ";"));
                data.setTakeEventIndex(rs.getInt("takeEventIndex"));
                data.setOpenNum(rs.getInt("openNum"));
                data.setRestTime(rs.getLong("restTime"));
                String userInfoList = rs.getString("userInfoList");
                if(!StringUtils.isNullOrEmpty(userInfoList)) {
                    data.setUserInfoList(JSONArray.parseArray(userInfoList, UserBaseInfo.class));
                }
                list.add(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            getGameServer().closeConnection(call, null);
        }
        return list;
    }

    /**
     * 商会副业
     */
    public List<UnionParergon> getUnionParergonList(){
        PreparedStatement call = null;
        String sql = "select * from t_u_union_parergon";
        List<UnionParergon> list = new ArrayList<>();
        try {
            call = getGameServer().getConnection().prepareStatement(sql);
            ResultSet rs = call.executeQuery();
            while (rs.next()) {
                UnionParergon data = new UnionParergon();
                data.setUnionId(rs.getString("unionId"));
                data.setParergonId(rs.getInt("parergonId"));
                data.setProgress(rs.getInt("progress"));
                data.setParergonTimes(rs.getInt("parergonTimes"));
                data.setPlayerIds(rs.getString("playerIds"));
                data.setDayRestoreTime(rs.getLong("dayRestoreTime"));
                list.add(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            getGameServer().closeConnection(call, null);
        }
        return list;
    }

    /**
     * 成员副业
     */
    public List<UnionParergonPlayer> getUnionParergonPlayerList(){
        PreparedStatement call = null;
        String sql = "select * from t_u_union_parergon_player";
        List<UnionParergonPlayer> list = new ArrayList<>();
        try {
            call = getGameServer().getConnection().prepareStatement(sql);
            ResultSet rs = call.executeQuery();
            while (rs.next()) {
                UnionParergonPlayer data = new UnionParergonPlayer();
                data.setUserId(rs.getLong("userId"));
                data.setOperateTimes(rs.getInt("operateTimes"));
                data.setLastRestoreTime(rs.getLong("lastRestoreTime"));
                data.setBargainTime(rs.getLong("bargainTime"));
                data.setBargainUnionUId(rs.getString("bargainUnionUId"));
                data.setTodayTimes(rs.getInt("todayTimes"));
                data.setTotalTimes(rs.getInt("totalTimes"));
                data.setHistoryTimes(rs.getInt("historyTimes"));
                data.setDayUnionUId(rs.getString("dayUnionUId"));
                data.setDayRestoreTime(rs.getLong("dayRestoreTime"));
                list.add(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            getGameServer().closeConnection(call, null);
        }
        return list;
    }

    /**
     * 副业商人
     */
    public List<UnionBussinessman> getUnionBussinessmanList(){
        PreparedStatement call = null;
        String sql = "select CONCAT('1',?,LPAD(bussinessId, 5, 0)) as bussinessId,unionId, disappearTime, productId, bargainPrice,bargainTimes,bargainNum,createTime,bargainValues from t_u_union_bussinessman where disappearTime > ?";
        List<UnionBussinessman> list = new ArrayList<>();
        try {
            call = getGameServer().getConnection().prepareStatement(sql);
            int i = 1;
            //call.setString(i++, getGameServer().getServerInfo().getChannelId() + "");
            String serverId = String.valueOf(getGameServer().getServerInfo().getServerId());
            call.setString(i++, serverId.substring(serverId.length() - 3));
            long now = System.currentTimeMillis() / 1000;
            call.setLong(i++, now);
            ResultSet rs = call.executeQuery();
            while (rs.next()) {
                UnionBussinessman data = new UnionBussinessman();
                data.setBussinessId(rs.getInt("bussinessId"));
                data.setUnionId(rs.getString("unionId"));
                data.setDisappearTime(rs.getLong("disappearTime"));
                data.setProductId(rs.getInt("productId"));
                data.setBargainPrice(rs.getLong("bargainPrice"));
                data.setBargainTimes(rs.getInt("bargainTimes"));
                data.setBargainNum(rs.getInt("bargainNum"));
                data.setCreateTime(rs.getLong("createTime"));
                String value = rs.getString("bargainValues");
                if(!StringUtils.isNullOrEmpty(value)){
                    data.setBargainValues(StringUtils.stringToIntegerList(value, ","));
                }
                list.add(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            getGameServer().closeConnection(call, null);
        }
        return list;

    }

    /**
     * 成员副业商人
     */
    public List<UnionBussinessmanDetail> getUnionBussinessmanDetailList(){
        PreparedStatement call = null;
        String sql = "select a.userId,a.bargainPrice,a.bargainTime,a.hasBuy, CONCAT('1',?,LPAD(a.bussinessId, 5, 0)) as bussinessId2 from t_u_union_bussinessman_detail a left join t_u_union_bussinessman b on a.bussinessId = b.bussinessId   where b.disappearTime > ?";
        List<UnionBussinessmanDetail> list = new ArrayList<>();
        try {
            call = getGameServer().getConnection().prepareStatement(sql);
            long now = System.currentTimeMillis() / 1000;
            int i = 1;
            //call.setString(i++, getGameServer().getServerInfo().getChannelId() + "");
            String serverId = String.valueOf(getGameServer().getServerInfo().getServerId());
            call.setString(i++, serverId.substring(serverId.length() - 3));
            call.setLong(i++, now);
            ResultSet rs = call.executeQuery();
            while (rs.next()) {
                UnionBussinessmanDetail data = new UnionBussinessmanDetail();
                data.setBussinessId(rs.getInt("bussinessId2"));
                data.setUserId(rs.getLong("userId"));
                data.setBargainPrice(rs.getLong("bargainPrice"));
                data.setBargainTime(rs.getLong("bargainTime"));
                data.setHasBuy(rs.getBoolean("hasBuy"));
                list.add(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            getGameServer().closeConnection(call, null);
        }
        return list;
    }
}
